<template>
  <div class="avatar-upload-container">
    <!-- 头像预览区域 -->
    <div class="avatar-preview">
      <img v-if="previewUrl" :src="previewUrl" alt="头像预览" class="avatar-image" />
      <el-icon v-else class="avatar-placeholder">
        <UserFilled />
      </el-icon>
    </div>

    <!-- 浏览按钮 -->
    <el-button @click="handleBrowseClick" size="small">浏览</el-button>

    <!-- 隐藏的文件输入框 -->
    <input
      ref="fileInputRef"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleFileChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { UserFilled } from '@element-plus/icons-vue'

// 预览图 URL
const previewUrl = ref<string | null>(null)

// 文件输入框引用
const fileInputRef = ref<HTMLInputElement | null>(null)

// 点击“浏览”按钮触发文件选择
const handleBrowseClick = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click()
  }
}

// 文件选择后的处理
const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]

  if (!file) return

  // 检查是否为图片
  if (!file.type.startsWith('image/')) {
    alert('请选择图片文件！')
    return
  }

  // 创建预览 URL
  const url = URL.createObjectURL(file)
  previewUrl.value = url

  // 可选：清除 input 值，以便下次可重复选择同一文件
  target.value = ''
}
</script>

<style scoped>
.avatar-upload-container {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-preview {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background-color: #f5f7fa;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  font-size: 36px;
  color: #909399;
}
</style>
